import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/common/osc_user_manager.dart';
import 'package:osc/models/entity/osc_medal_entity.dart';
import 'package:osc/models/pop_result/pop_result.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/res/strings.dart';
import 'package:osc/ui/pages/account/login_page.dart';
import 'package:osc/ui/widgets/image_loader.dart';
import 'package:osc/ui/widgets/no_data_widget.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:osc/utils/string_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'medal_detail_page.dart';

///勋章
class MedalList extends StatefulWidget {
  final int userId;
  final int type;
  ///1:身份勋章，2:问答勋章，3:活动勋章，4:贡献勋章，
  const MedalList({Key key, @required this.userId, this.type = 1}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new MedalListState(userId, type);
  }
}

class MedalListState extends State<MedalList>  {
  final int userId;
  final int type;
  MedalListState(this.userId, this.type);

  HttpRepository httpRepository;
  String pageToken;
  int size = 0;
  int bannerCount = 3;
  bool isLoadedData = false;


  double paddingChildVertical = Dimens.gap_view_normal;


  List<OscMedal> list;

  RefreshController controller = RefreshController(initialRefresh: true);
  ScrollPhysics scrollPhysics = ScrollPhysics();

  @override
  void initState() {
    super.initState();
    httpRepository = HttpRepository();
  }

  @override
  void dispose() {
    super.dispose();
    controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      controller: controller,
      onRefresh: refresh,
      onLoading: loadMore,
      enablePullUp: false,
      child: buildGridView(),
    );
  }

  buildGridView(){
    return GridView.builder(
      padding: EdgeInsets.symmetric(vertical: Dimens.gap_activity_horizontal),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
        ),
        itemBuilder: (BuildContext context, int index) {
          if (size == 0) {
            return NoDataWidget();
          } else {
            return buildListItem(index);
          }
        },
        itemCount: isLoadedData && size == 0? 1 : size,
    );
  }

  buildListItem(int index){
    OscMedal item = list.elementAt(index);
    String obtainDate = "";
    if(!StringUtil.isEmpty(item.obtainDate)){
      obtainDate = DateUtil.getDateStrByTimeStr(item.obtainDate, format: DateFormat.YEAR_MONTH_DAY);
    }
    return GestureDetector(
      onTap: (){
        print("---ontap");
        jump2PageForResult(MedalPage(medal: item,));
      },
      child: Column(
        children: <Widget>[
          Container(
              padding: EdgeInsets.symmetric(horizontal: Dimens.gap_activity_horizontal),
            margin: EdgeInsets.symmetric(horizontal: Dimens.gap_view_normal),
            child: ImageLoader(url: item.show? item.lightLogo : item.grayLogo,),
          ),
          buildText(item.title, Colors.black, Dimens.font_sp14),
          buildText(obtainDate, Colors.black54, Dimens.font_sp12),
        ],
      ),
    );
  }


  buildText(String data, Color color, double fontSize) {
    return SmallWidgets.buildText(data, color, fontSize);
  }

  refresh() async{
    list?.clear();
    await loadMore();
  }


  loadMore() async{
    List<OscMedal> tempList;
    await httpRepository.getMedalist(userId: userId, type: type).then((resp){
      if(resp != null && resp.success){
        if(resp != null){
          tempList = resp.listResult;
          if(pageToken == null){
            list = tempList;
          } else {
            list.addAll(tempList);
          }
          size = list?.length??0;
        }
      }
    });

    if(mounted) {
      setState(() {
        controller.refreshCompleted();
        controller.loadComplete();
      });
    }
  }

  jump2PageForResult(Widget page, {bool checkLogin = false}) {
    if(checkLogin){
      if(OscUserManager.getInstance().isLogin()){
        jumpToPageForResult(page);
      } else {
        jumpToPageForResult(LoginPage());
        showTips(StringIds.userNoLogin);
      }
    } else {
      jumpToPageForResult(page);
    }
  }
  jumpToPageForResult(Widget page) {
    NavigatorUtil.pushPageForResult<PopResult>(context, page).then((result) {
      if (result != null) {
        switch (result.id) {
          case PopResult.ID_LOGIN:
            break;
        }
      }
    });
  }

  showTips(String msg){
    PdUtil.showToast(msg: msg);
  }

}
